﻿#include "DialogSendReply.h"
#include "ui_DialogSendReply.h"
#include "quihelperdata.h"
#include "CrcUtils.h"

DialogSendReply::DialogSendReply(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogSendReply)
{
    ui->setupUi(this);
}

DialogSendReply::~DialogSendReply()
{
    if(_sendReply!=nullptr)
    {
        disconnect(_sendReply,&BaseSendReply::DataReceive,this,&DialogSendReply::OnDataReceive);
    }

    delete ui;
}

void DialogSendReply::SetSendReply(BaseSendReply *sendReply)
{
    _sendReply=sendReply;
    ui->lineIp->setText(sendReply->GetCommunicationParam());
    SetStstus(sendReply->IsConnected()?"green":"red");
    connect(_sendReply,&BaseSendReply::DataReceive,this,&DialogSendReply::OnDataReceive,Qt::AutoConnection);
}

void DialogSendReply::closeEvent(QCloseEvent *event)
{
    QDialog::closeEvent(event);
}

void DialogSendReply::SetStstus(QString colorName)
{
    ui->lblStatus->setStyleSheet(QString("background-color: %1;").arg(colorName));
}

void DialogSendReply::on_btnSendReply_clicked()
{
    QByteArray send={"\x01\x02\xff"};
    QByteArray rec;
    if(_sendReply->SendReply(send,rec))
    {
        AddNewLine(QString::fromUtf8(rec));
        qDebug()<<"sned:"<<send<<"rec:";
    }
}

void DialogSendReply::OnDataReceive(QByteArray data)
{
    AddNewLine(QString::fromUtf8(data));
}

void DialogSendReply::AddNewLine(QString line)
{
    QTextCursor cursor = ui->txtMsg->textCursor();
    // 移动光标到文本末尾
    cursor.movePosition(QTextCursor::End);
    // 插入新的一行文本
    cursor.insertBlock();
    cursor.insertText(line);
    // 设置光标到新的一行
    ui->txtMsg->setTextCursor(cursor);
}

void DialogSendReply::on_btnCrc_clicked()
{
    QByteArray sendbuf= QUIHelperData::hexStrToByteArray(ui->txtCommand->text());
    unsigned short incrc16=CRCUtils::CRC16_Check(reinterpret_cast<unsigned char *>(sendbuf.data()),sendbuf.count());
    QByteArray crc=CRCUtils::ParaseByteArray(incrc16);
    ui->txtCrc->setText(QUIHelperData::byteArrayToHexStr(crc));
}

void DialogSendReply::on_btnSend_clicked()
{
    QString fullCmd=ui->txtCommand->text()+ui->txtCrc->text();
    QByteArray sendbuf= QUIHelperData::hexStrToByteArray(fullCmd);
    QByteArray rec;
    _sendReply->SendReply(sendbuf,rec);
    QString recStr=QUIHelperData::byteArrayToHexStr(rec);
    ui->txtMsg->append(recStr+"\n");
}
